package com.zenkeeuk.bookerfornfc.client.android;

import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;

import org.ksoap2.serialization.SoapObject;

import com.zenkeeuk.bookerfornfc.client.android.book.LabBookInfo;
import com.zenkeeuk.bookerfornfc.client.android.book.LabBookListAdapter;
import com.zenkeeuk.bookerfornfc.client.android.http.HttpUtil;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class LabSearchActivity extends Activity {

	private ProgressDialog myDialog = null;
	private String message;
	private Contents.GET_LABSEARCH_BOOK_MSG getSearchStatus = Contents.GET_LABSEARCH_BOOK_MSG.ERROR;
	private String labSearchBookName = null;
	
	List<LabBookInfo> listResilt;
	
	
	@Override
	public void onCreate(Bundle icicle) {
	    super.onCreate(icicle);
	    requestWindowFeature(Window.FEATURE_NO_TITLE);
	    setContentView(R.layout.labsearchlist);
	    
	    myDialog = ProgressDialog.show(this, 
	    		getResources().getString(R.string.progress_labsearch_title),
	    		getResources().getString(R.string.progress_labsearch_notice), true);
		
	    labSearchBookName = this.getIntent().getStringExtra(Contents.INTENT_EXTRA_LABSEARCH_BOOK_NAME_KEY);
	    if (labSearchBookName != null || labSearchBookName.trim().equals("")){
	    	new Thread(getSearchResult).start();
	    } else {
	    	myDialog.dismiss();
	    	Toast.makeText(getApplicationContext(), 
	    			getResources().getString(R.string.progress_getbookinfo_notfound),
	    			Toast.LENGTH_SHORT).show();
	    	this.finish();
	    }
	}
	
	@Override
 	public boolean onCreateOptionsMenu(Menu menu) {
	    super.onCreateOptionsMenu(menu);
	    menu.add(0, Contents.HOME_ID, 0, R.string.menu_home)
	        .setIcon(R.drawable.homebtn);
	    menu.add(0, Contents.HISTORY_ID, 0, R.string.menu_history)
	        .setIcon(R.drawable.historybtn);
	    menu.add(0, Contents.SETTINGS_ID, 0, R.string.menu_settings)
	        .setIcon(R.drawable.settingbtn);
	    return true;
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
	    switch (item.getItemId()) {
	        case Contents.HOME_ID: {
	        	Intent intent = new Intent(Intent.ACTION_VIEW);
		        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
		        intent.setClassName(this, HomePageActivity.class.getName());
		        startActivity(intent);
		        break;
	        }
	        case Contents.HISTORY_ID: {
		    	Intent intent = new Intent(Intent.ACTION_VIEW);
			    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
			    intent.setClassName(this, HomePageActivity.class.getName());
			    intent.putExtra(Contents.INTENT_EXTRA_RETURN_TO_TAP_KEY, 1);
			    startActivity(intent);
			    break;
		    }
	        case Contents.SETTINGS_ID: {
	        	Intent intent = new Intent(Intent.ACTION_VIEW);
			    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
			    intent.setClassName(this, HomePageActivity.class.getName());
			    intent.putExtra(Contents.INTENT_EXTRA_RETURN_TO_TAP_KEY, 2);
			    startActivity(intent);
			    break;
	        }
	    }
	    return super.onOptionsItemSelected(item);
	}
	
	public Runnable getSearchResult = new Runnable() {
		public void run() {
			if(labSearchBookName!=null){
				
				try {
					
					String[] properties = { "bookName" };
					String[] data = {labSearchBookName};
					
					SoapObject result = HttpUtil.getWebServiceData("http://www.zenkee.com/", 
							Contents.LAB_SERVICE_HOST_ADDRESS, 
							"SearchBook",
							"http://www.zenkee.com/SearchBook",
							properties, data,
							"SearchBookResult");
					
					parseLabBookInfo(result);
					
					getSearchStatus = Contents.GET_LABSEARCH_BOOK_MSG.OK;
					message = getResources().getString(R.string.progress_labsearch_success);
					
				} catch(Exception e) {
					getSearchStatus = Contents.GET_LABSEARCH_BOOK_MSG.ERROR;
					message = getResources().getString(R.string.progress_labsearch_failed);
				}
				
				messageHandler.sendMessage(messageHandler.obtainMessage());
			}
		}
	};
	
	private void parseLabBookInfo(SoapObject result) {
		listResilt = new ArrayList<LabBookInfo>();
		LabBookInfo labBook = new LabBookInfo();
		
		int iCount = result.getPropertyCount();
		
		for (int i=0;i<iCount;i++) {
			SoapObject soapObjBook = (SoapObject)result.getProperty(i);
			labBook = new LabBookInfo();
			labBook.setBookName(getWebserviceValue(soapObjBook.getPropertyAsString("BookName")));
			labBook.setBookuid(getWebserviceValue(soapObjBook.getPropertyAsString("BookUID")));
			labBook.setBookisbn(getWebserviceValue(soapObjBook.getPropertyAsString("icbc")));
			labBook.setRemark(getWebserviceValue(soapObjBook.getPropertyAsString("remark"), true));
			labBook.setLibraryName(getWebserviceValue(soapObjBook.getPropertyAsString("LibraryName")));
			labBook.setTimek(getWebserviceValue(soapObjBook.getPropertyAsString("time")));
			labBook.setLocation(getWebserviceValue(soapObjBook.getPropertyAsString("Location")));
			
			if (!labBook.getRemark().equals("未借")){
				labBook.setToReturnTime(soapObjBook.getPropertyAsString("ToReturnTime"));
			}
			
			listResilt.add(labBook);
		}
	}
	
	private String getWebserviceValue(String value) {
		if (value == null||value.equals("anyType{}")) {
			value = "";
		}
		return value;
	}
	
	private String getWebserviceValue(String value, boolean isRemark) {
		
		if (value == null||value.equals("anyType{}")) {
			value = "";
		}
		
		if (isRemark&& value.equals("")){
			value = "未借";
		}
		
		return value;
	}
	
	private void setViews() {
		TextView lab_search_title = (TextView)findViewById(R.id.lab_search_title);
		MessageFormat message = new MessageFormat(getResources().getString(R.string.labsearch_result_lable));
		lab_search_title.setText(message.format(new String[]{labSearchBookName}));
		
		TextView lab_search_summary = (TextView)findViewById(R.id.lab_search_summary);
		message = new MessageFormat(getResources().getString(R.string.labsearch_result_summary));
		lab_search_summary.setText(message.format(new String[]{String.valueOf(listResilt.size())}));
		
		ListView lv = (ListView) this.findViewById(R.id.labbook_list);
		LabBookListAdapter listAdapter;
		if (listResilt.size() > 0) {
			listAdapter = new LabBookListAdapter(this, listResilt);
		} else {
			listAdapter = null;
		}
		
		lv.setAdapter(listAdapter);
		
		lv.setOnItemClickListener(new OnItemClickListener(){
			public void onItemClick(AdapterView<?> parent, View view, int position,
					long id) {
				LabBookInfo book =  listResilt.get(position);
		  	  	Toast.makeText(getApplicationContext(), book.getBookName(), Toast.LENGTH_SHORT).show();
		  	  	
		        Intent intent = new Intent(getBaseContext(), LabBookDetailActivity.class);
			    intent.putExtra(Contents.INTENT_EXTRA_LABBOOK_BookName_KEY, book.getBookName());
			    intent.putExtra(Contents.INTENT_EXTRA_LABBOOK_BookUID_KEY, book.getBookuid());
			    intent.putExtra(Contents.INTENT_EXTRA_LABBOOK_ISBN_KEY, book.getBookisbn());
			    intent.putExtra(Contents.INTENT_EXTRA_LABBOOK_remark_KEY, book.getRemark());
			    intent.putExtra(Contents.INTENT_EXTRA_LABBOOK_time_KEY, book.getTime());
			    intent.putExtra(Contents.INTENT_EXTRA_LABBOOK_LibraryName_KEY, book.getLibraryName());
			    intent.putExtra(Contents.INTENT_EXTRA_LABBOOK_Location_KEY, book.getLocation());
			    intent.putExtra(Contents.INTENT_EXTRA_LABBOOK_ToReturnTime_KEY, book.getToReturnTime());
		        startActivity(intent);
		  	}
		});
	}
	
	
	private Handler messageHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
        	myDialog.dismiss();
        	Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show();
            
        	switch(getSearchStatus){
        		case OK:
        			setViews();
        			break;
        		case ERROR:
        			finish();
        			break;
        	}
        }
	};
	
}
